import React, { useState, useEffect } from 'react';
import _ from 'lodash';
import { Button, Form, Input, message } from 'antd';
import DraggableModal from '@/components/DraggableModal';
import DebounceWrapper from '@/components/DebounceWrapper';
import { modifyResponseCodeMessage } from '@/services/system/responseCode';

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 17 },
};
const DebounceButton = DebounceWrapper(Button);

export default ({ visible, options, closeModal, updateList }) => {
  const { id, returnMsg } = options;
  const [form] = Form.useForm();
  const [actionLoading, setActionLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      return form.setFieldsValue({ returnMsg: returnMsg || '' });
    }
    form.resetFields();
  }, [visible]);

  const handleCancel = () => {
    if (!actionLoading) {
      closeModal();
    }
  };
  const handleConfirm = () => {
    form.validateFields().then((values) => {
      setActionLoading(true);
      const params = _.assign({ id }, values);
      // console.log('入参:', params);
      modifyResponseCodeMessage(params)
        .then(() => {
          closeModal();
          updateList();
          message.success('响应提示信息编辑成功');
          setActionLoading(false);
        })
        .catch(() => {
          setActionLoading(false);
        });
    });
  };

  return (
    <DraggableModal
      title={`编辑响应提示信息`}
      visible={visible}
      onCancel={handleCancel}
      footer={[
        <DebounceButton key="cancel" disabled={actionLoading} onClick={closeModal}>
          取消
        </DebounceButton>,
        <DebounceButton
          key="confirm"
          type="primary"
          loading={actionLoading}
          onClick={handleConfirm}
        >
          提交
        </DebounceButton>,
      ]}
    >
      <Form {...layout} form={form} name="response-msg-form">
        <Form.Item
          name="returnMsg"
          label="提示信息"
          initialValue={''}
          rules={[{ required: true, whitespace: true, message: '请输入提示信息' }]}
        >
          <Input allowClear maxLength={64} autoComplete="off" placeholder={'请输入提示信息'} />
        </Form.Item>
      </Form>
    </DraggableModal>
  );
};
